import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login, getUserInfo, logout as userLogout, getRoutes } from '../api/user'
import type { UserInfo } from './types'
import { resetRouter } from '../router'
import type { DynamicRouteComponent } from '../router'

export const useUserStore = defineStore('user', () => {
  const token = ref(sessionStorage.getItem('token') || '')
  const userInfo = ref<UserInfo | null>(null)
  const menuList = ref<DynamicRouteComponent[]>([])

  // 登录
  const loginAction = async (username: string, password: string) => {
    const res = await login({ username, password })
    token.value = res.token
    sessionStorage.setItem('token', res.token)
  }

  // 获取用户信息
  const getUserInfoAction = async () => {
    if (!token.value) return
    const res = await getUserInfo()
    userInfo.value = res
  }

  // 获取路由配置
  const getRoutesAction = async (): Promise<DynamicRouteComponent[]> => {
    if (!token.value) return []
    const routes = await getRoutes() as unknown as DynamicRouteComponent[]
    menuList.value = routes
    return routes
  }

  // 登出
  const logout = async () => {
    await userLogout()
    token.value = ''
    userInfo.value = null
    menuList.value = []
    sessionStorage.removeItem('token')
    resetRouter() // 重置路由
  }

  return {
    token,
    userInfo,
    menuList,
    loginAction,
    getUserInfoAction,
    getRoutesAction,
    logout,
    username: computed(() => userInfo.value?.username || ''),
    hasUserInfo: computed(() => !!userInfo.value)
  }
}) 